﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ZDT.Task.TPurview;
using System.Windows.Forms;
using System.Threading;

namespace ZDT.UI.Web
{
    public class WebBrowseTask : PurviewTask
    {
        public MyWebBrowser WebBrowser = null;
        protected override void Init()
        {
            base.Init();
            WebBrowser.Navigate(Setting.BaseUrl);
        }
        protected override void One(PurviewInfo info)
        {
            base.One(info);
            WebBrowser.Tag = info;
            WebBrowser.Url = new Uri(Setting.BaseUrl);
            WebBrowser.Navigated += WebBrowserNavigatedEventHandler;
        }

        private void WebBrowserNavigatedEventHandler(object sender, WebBrowserNavigatedEventArgs e)
        {
            PurviewInfo info = WebBrowser.Tag as PurviewInfo;
            System.Threading.Thread tash = new System.Threading.Thread(() =>
            {
                NavigateAfter(e.Url.ToString(), info);
                NextNavigate(e.Url.ToString(), info);
            });
            tash.Start();
        }
        private void Navigate(string url, int wait, PurviewInfo info)
        {
            WebBrowser.Navigate(url);
            Thread.Sleep(wait * 1000);
            NextNavigate(url, info);
        }
        private void NavigateAfter(string url, PurviewInfo info)
        {
            string key = string.Empty;
            if (info.LoginUrl == url)
            {
                key = Setting.LoginUrlFmt;
            }
            else if (info.AddUrl == url)
            {
                key = Setting.AddUrlFmt;
            }
            else if (info.RefreshUrl == url)
            {
                key = Setting.RefreshUrlFmt;
            }
            if (!string.IsNullOrEmpty(key))
            {
                foreach (var item in Setting.RefScripts)
                {
                    WebBrowser.AddScripRef(item);
                }
                string scriptPath = Setting.UrlScripts[key];
                WebBrowser.AddScripBlock(App.GConfig.Scripts + scriptPath);
            }
        }

        private void NextNavigate(string url, PurviewInfo info)
        {
            string nextUrl = string.Empty;
            int wait = -1;
            if (Setting.BaseUrl == url)
            {
                Thread.Sleep(Setting.Wait * 1000);
                nextUrl = info.LoginUrl;
                wait = Setting.LoginWait;
            }
            else if (info.LoginUrl == url)
            {
                nextUrl = info.AddUrl;
                wait = Setting.AddWait;
            }
            else if (info.AddUrl == url)
            {
                nextUrl = info.RefreshUrl;
                wait = Setting.RefreshWait;
            }
            if (wait > -1)
            {
                Navigate(nextUrl, wait, info);
            }
        }
    }
}
